<template>
	<el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large" @keyup.enter="login">
		<el-form-item prop="mobile">
			<el-input v-model="form.mobile" prefix-icon="el-icon-iphone" clearable
					  :placeholder="$t('login.mobilePlaceholder')">
				<template #prepend>+86</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="smsCode" style="margin-bottom: 35px;">
			<div class="login-msg-yzm">
				<el-input v-model="form.smsCode" prefix-icon="el-icon-unlock" clearable
						  :placeholder="$t('login.smsPlaceholder')"></el-input>
				<el-button @click="sendSms" :disabled="disabled">{{ this.$t('login.smsGet') }}
					<span v-if="disabled"> ({{ time }})</span>
				</el-button>
			</div>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" style="width: 100%;" :loading="isLogin" round @click="login">{{
					$t('login.signIn')
				}}
			</el-button>
		</el-form-item>
		<div class="login-reg">
			{{ $t('login.noAccount') }}
			<router-link to="/user_register">{{ $t('login.createAccount') }}</router-link>
		</div>
	</el-form>
</template>

<script>
export default {
	data() {
		return {
			form: {
				mobile: "",
				smsCode: "",
			},
			rules: {
				mobile: [
					{required: true, message: this.$t('login.mobileError')}
				],
				smsCode: [
					{required: true, message: this.$t('login.smsError')}
				]
			},
			disabled: false,
			time: 0,
			isLogin: false,
		}
	},
	mounted() {

	},
	methods: {
		async sendSms() {
			const validate = await this.$refs.loginForm.validateField("mobile").catch(() => {
			});
			if (!validate) {
				return false
			}

			// 发送短信
			await this.$API.auth.sms.post({
				mobile: this.form.mobile,
				smsType: 'LOGIN'
			});

			this.$message.success(this.$t('login.smsSent'))
			this.disabled = true
			this.time = 60
			const t = setInterval(() => {
				this.time -= 1
				if (this.time < 1) {
					clearInterval(t)
					this.disabled = false
					this.time = 0
				}
			}, 1000);
		},
		async login() {
			const validate = await this.$refs.loginForm.validate().catch(() => {
			});
			if (!validate) {
				return false
			}

			const data = {
				mobile: this.form.mobile,
				smsCode: this.form.smsCode
			};

			// 手机号登录
			this.$API.auth.mobileLogin.post(data).then(loginInfo => {
				this.$TOOL.cookie.set("TOKEN", loginInfo.accessToken, {
					expires: this.form.autologin ? loginInfo.expires : 0
				})
				this.$TOOL.data.set("USER_INFO", loginInfo)

				// 获取菜单
				this.$API.manage.permission.oneself.get().then(menu => {
					if (menu.length === 0) {
						this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
							type: 'error',
							center: true
						})
					} else {
						this.$TOOL.data.set("MENU", menu)
						this.$TOOL.data.set("PERMISSIONS", loginInfo.permissions)
					}

					this.$router.replace({
						path: '/'
					})
					this.$message.success("登录成功")

				});

			}).catch(() => {
			});
		}
	}
}
</script>

<style>

</style>
